const { BrowserWindow, MenuItem, Menu, ipcMain, globalShortcut } = require('electron');
const mEmitter = require('../Manager/eventEmitter');
const mTool = require('../Tool/mTool');
const path = require('path');
const puppeteer = require('puppeteer-core');

// let grabTicket_MainWindow = null;
// function createWindow() {
//     //创建窗口
//     grabTicket_MainWindow = new BrowserWindow({
//         x: 100,
//         y: 10,
//         width: 900,
//         height: 700,
//         alwaysOnTop: true,
//         show: false,
//         autoHideMenuBar: true,
//         backgroundColor: '#f0ffff',
//         title: "计调辅助工具",
//         // webPreferences: {
//         //   preload: path.join(__dirname, 'preload.js')
//         // }
//     })

//     // filePaths.forEach(filePath => {
//     //   console.log(path.basename(filePath));
//     // })
//     // console.log(JSON.stringify(filePaths));

//     // 加载 index.html
//     // mainWindow.loadFile('index.html')
//     grabTicket_MainWindow.loadURL('https://fsteam.dmqwl.com//#/travelLogin')

//     grabTicket_MainWindow.once("ready-to-show", () => {
//         grabTicket_MainWindow.show();

//     })

//     grabTicket_MainWindow.on('closed', () => {
//         mEmitter.emit('displayMainWindow');
//         grabTicket_MainWindow = null
//     })

//     grabTicket_MainWindow.webContents.on('did-finish-load', () => {
//         let webTitle = grabTicket_MainWindow.webContents.getTitle();

//         if (webTitle === "佛山团队预订系统") {
//             mTool.addScript2Web(grabTicket_MainWindow.webContents, path.join(__dirname, "script/autoLogin.js"));
//         }
//         //  else if (webTitle === "旅行社团队预订系统") {
//         //     console.log(webTitle);

//         // }
//     })
//     grabTicket_MainWindow.webContents.on('context-menu', (event, params) => {
//         const menu = new Menu();
//         menu.append(new MenuItem({
//             label: '注入脚本',
//             click: () => {
//                 mTool.addScript2Web(grabTicket_MainWindow.webContents, path.join(__dirname, "script/autoGrabTicket.js"));
//             }
//         }))

//         menu.popup(grabTicket_MainWindow, params.x, params.y);
//     })
// }

let name, day, session, Vip, noVip, teamType;
let optionWindow;
function createOptionWindow() {
    optionWindow = new BrowserWindow({
        x: 100,
        y: 10,
        width: 600,
        height: 500,
        alwaysOnTop: true,
        show: false,
        autoHideMenuBar: true,
        backgroundColor: '#f0ffff',
        title: "设置抢票信息",
        webPreferences: {
            preload: path.join(__dirname, 'script/option_preload.js')
        }
    })
    optionWindow.once("ready-to-show", () => {
        optionWindow.show();
    })
    optionWindow.loadFile(path.join(__dirname, "option.html"))

}
function createWindowTest() {
    (async () => {
        try {
            // 启动浏览器
            const browser = await puppeteer.launch({
                executablePath: path.resolve('chrome-win64\\chrome.exe'),
                headless: false
            });
            var checkDayCount = 0;//成功检查日期计数
            var checkDayInterval = 400;//检查日期间隔
            // 打开一个新页面  
            const page = await browser.newPage();
            // 导航到指定的网址  
            page.on('load', () => {
                page.title().then(title => console.log(title));
                //输入旅行社名称
                page.$('input[placeholder = "旅行社名称"]').then(async ele => {
                    await ele.type('广东抖游国际旅行社有限公司');
                    //输入密码
                    page.$('input[placeholder = "密码"]').then(async ele => {
                        await ele.type('78245900');
                        //输入验证码
                        page.$('input[placeholder = "验证码"]').then(async ele => {
                            await ele.type('123456');
                            //点击'登录'
                            await page.$$eval('span', (eles) => {
                                for (let ele of eles) {
                                    if (ele.innerText === '登录') {
                                        ele.click();
                                    }
                                }
                            })
                            await page.evaluate(async () => {
                                await new Promise(resolve => {
                                    let btnMonitor = setInterval(() => {
                                        for (const ele of document.querySelectorAll('span')) {
                                            if (ele.innerText === '订单预订') {
                                                clearInterval(btnMonitor);
                                                ele.click();
                                                resolve();
                                            }
                                        }
                                    }, 500);
                                });
                            })
                            setTimeout(() => {
                                checkDay();
                            }, 500);
                        })
                    })
                })
            })

            //查询日期,并预定
            async function checkDay() {
                let refreshBtn = await page.evaluateHandle(() => {
                    return Array.from(document.querySelectorAll('use')).find(ele => ele.getAttribute('xlink:href') === '#icon-sync');
                });
                refreshBtn.click();
                setTimeout(async () => {
                    await page.click('input[placeholder = "选择日期"]');
                    setTimeout(async () => {
                        let isContinue = await page.$$eval('div', (eles, day) => {
                            for (let ele of eles) {
                                //检查目标日期是否可用
                                if (ele.innerHTML.replace(/\s/g, '') === '<span>' + day + '</span>') {
                                    if (ele.parentElement.classList.contains('available')) {
                                        ele.click();
                                        return false;
                                    } else if (ele.parentElement.classList.contains('prev-month') || ele.parentElement.classList.contains('next-month')) {
                                        continue;
                                    } else {
                                        return true;
                                    }
                                }
                            }
                        }, day)
                        if (isContinue) {
                            checkDay();
                        } else {
                            checkDayCount++;
                            checkDayInterval = 150;
                            if (checkDayCount > 3) {
                                checkDayInterval = 400;
                                checkDayCount = 0;
                                autoFillInfo();
                            } else {
                                checkDay();
                            }
                        }
                    }, checkDayInterval)
                }, 100);
            }
            async function autoFillInfo() {
                //填入出发地
                await page.type('input[placeholder = "请输入客源地"]', '广州市');
                await page.evaluateHandle(() => {
                    let monitor = setInterval(() => {
                        for (let ele of document.querySelectorAll('li')) {
                            if (ele.innerHTML.replace(/\s/g, '') === '广州市') {
                                clearInterval(monitor);
                                ele.click();
                                return ele;
                            }
                        }
                    }, 100);
                })
                //填入导游信息
                await page.type('input[placeholder = "请输入导游名称或手机号"]', name);
                await page.evaluateHandle((name) => {
                    let amonitor = setInterval(() => {
                        for (let ele of document.querySelectorAll('span')) {
                            if (ele.innerHTML.replace(/\s/g, '') === (name + "——")) {
                                clearInterval(amonitor);
                                ele.parentElement.click();
                                return ele;
                            }
                        }
                    }, 100);
                }, name)
                await page.evaluate((session, Vip, noVip, teamType) => {
                    var inputEvent = new Event('input', {
                        bubbles: true,
                        cancelable: true
                    });
                    const aaa = setInterval(() => {
                        document.querySelectorAll("span").forEach((ele) => {
                            //选择表演场次
                            if (ele.innerText === session) {
                                clearInterval(aaa);
                                ele.click();

                                //输入预定席位
                                let bbb = setInterval(() => {
                                    var inputs = document.querySelectorAll("input");
                                    var isVip = true;
                                    for (let i = 0; i < inputs.length; i++) {
                                        if (inputs[i].placeholder == "请输入数量") {
                                            if (bbb) {
                                                clearInterval(bbb);
                                            }
                                            if (isVip) {
                                                inputs[i].value = Vip;
                                                inputs[i].dispatchEvent(inputEvent);
                                                isVip = false;
                                            } else {
                                                inputs[i].value = noVip;
                                                inputs[i].dispatchEvent(inputEvent);

                                                // 选择团队类型
                                                let ccc = setInterval(() => {
                                                    document.querySelectorAll("span").forEach((ele) => {
                                                        if (ele.innerText === teamType) {
                                                            clearInterval(ccc);
                                                            ele.click();
                                                            for (let eee of document.querySelectorAll("span")) {
                                                                if (eee.innerText === "立即预订") {
                                                                    eee.click();
                                                                    break;
                                                                }
                                                            }
                                                        }

                                                    })
                                                }, 100);
                                            }
                                        }
                                    }
                                }, 500);
                            }
                        })
                    }, 500);
                }, session, Vip, noVip, teamType)
            }

            await page.goto('https://fsteam.dmqwl.com//#/travelLogin'); // 将'https://www.example.com'替换为你想要打开的网站地址  
            // 等待页面加载完成或执行其他操作...  
            // 最后，记得关闭浏览器  
            // await browser.close();
        } catch (error) {
            // console.error('Error opening the website:', error);
        }
    })();
}



async function selectByInnerHTML(page, className, targetStr) {
    await page.$$eval(className, (eles) => {
        for (let ele of eles) {
            if (ele.innerHTML.replace(/\s/g, '') === targetStr) {
                return ele;
            }
        }
    })
}

ipcMain.on('start', (event, name_, day_, session_, Vip_, noVip_, teamType_) => {
    console.log(name_, day_, session_, Vip_, noVip_, teamType_);
    name = name_;
    day = day_;
    session = session_;
    Vip = Vip_;
    noVip = noVip_;
    teamType = teamType_;
    if (optionWindow) {
        optionWindow.close();
    }
    createWindowTest();
})

module.exports = {
    createOptionWindow,
    createWindowTest,
}